<?php
/**
 * Created by IntelliJ IDEA.
 * User: jimmyhsu
 * Date: 2017/4/18
 * Time: 01:10
 */
date_default_timezone_set("Asia/Shanghai");
include ("../Teacher/db/conn.php");
$username = $_POST['username'];
$password = $_POST['password'];
$course_id = $_POST['course_id'];
$student_tokens = $_POST['tokens'];
$source = $_POST['source'];

$sql = "select * from userinfo natural join takes where name='$username' and password='".md5($password)."' and course_id='$course_id' and position='assistant'";

$result = mysqli_query($cn, $sql);
if (mysqli_num_rows($result) > 0) {
    $tokens = explode(";", $student_tokens);
    foreach ($tokens as $token) {
        if ($source == 0) {
            $sql = "select name from userinfo where token='$token'";
            $query = mysqli_query($cn, $sql);
            $row = mysqli_fetch_array($query);
            $sql = "insert into attends values('".$row['name']."', '$course_id', '".date("Y-m-d")."')";
            mysqli_query($cn, $sql);
        } else if ($source == 1) {
            if ($token != '') {
                $sql = "insert into attends values('$token', '$course_id', '" . date("Y-m-d") . "')";
                mysqli_query($cn, $sql);
            }
        } else {
            die("invalid source");
        }

    }
    echo "success";
} else {
    echo "permission";
}